from selenium.common import NoSuchElementException, TimeoutException
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait

from config import setting
from config.operationConfig import OperationConfig
from utils.logging_tool.recordlog import logs


class BasePage(object):

    def __init__(self, driver):
        # 浏览器对象初始化
        self.title = None
        self.__driver = driver
        # 显示等待初始化,设置等待最长时间、轮询的频率以及在等待期间遇到的异常处理
        self.__wait = WebDriverWait(self.__driver, setting.WAIT_TIME, setting.POLL_TIME,
                                    ignored_exceptions=[TimeoutException])
        self.conf = OperationConfig()

    def base_open_url(self, url):
        """ 打开测试页面 """
        if url.startswith('http') or url.startswith('https'):
            self.__driver.get(url)
            logs.info(f'打开页面：{url}')
        else:
            new_url = self.conf.get_host('host') + url
            self.__driver.get(new_url)
            logs.info(f'打开页面：{new_url}')

    def base_find_element_exist(self, by, value):
        """ 查找操作 """
        try:
            element = self.__wait.until(ec.presence_of_element_located((by, value)))
            return element
        except Exception as e:
            return False

    def base_send_keys(self, locator: tuple, data):
        """ 输入操作 """
        try:
            element = self.base_find_element_exist(*locator)
            element.clear()
            element.send_keys(data)
        except NoSuchElementException as e:
            raise e

    def base_click(self, locator: tuple, force=False):
        """ 点击操作 """
        try:
            element = self.base_find_element_exist(*locator)
            if not force:
                # js 脚本点击方式
                self.__driver.execute_script("arguments[0].click()", element)
            else:
                self.__driver.execute_script("arguments[0].click({force:true})", element)
        except NoSuchElementException as e:
            raise e
